package com.zee.demo.utils;

import android.content.Context;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class CommonUtil {
    private static final String TAG = "AvatarSDK";

    /**
     * 读取外部缓存目录下的JSON文件内容
     * @param context 上下文
     * @param fileName JSON文件名（如"config.json"）
     * @return JSON文件内容字符串，读取失败返回null
     */
    public static String readJsonFromExternalCache(Context context, String fileName) {
        // 获取外部缓存目录
        File externalCacheDir = context.getExternalCacheDir();
        if (externalCacheDir == null) {
            Log.e(TAG, "无法获取外部缓存目录");
            return null;
        }

        // 构建完整文件路径
        File jsonFile = new File(externalCacheDir, fileName);

        // 检查文件是否存在
        if (!jsonFile.exists() || !jsonFile.isFile()) {
            Log.e(TAG, "文件不存在: " + jsonFile.getAbsolutePath());
            return null;
        }

        // 读取文件内容
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader reader = null;
        try {
            FileInputStream fis = new FileInputStream(jsonFile);
            reader = new BufferedReader(new InputStreamReader(fis));

            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            return stringBuilder.toString();
        } catch (IOException e) {
            Log.e(TAG, "读取文件失败", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    Log.e(TAG, "关闭流失败", e);
                }
            }
        }
        return null;
    }
}
